package sk.xorty.quartz;

import org.junit.Assert;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.io.PrintStream;

/**
 * This job calculates and prints (probable) prime numbers to stdout.
 */
public class PrimeNumbersJob implements Job {

    // injected values from jobContext
    private int primeFrom;
    private int primeTo;
    private PrintStream outStream;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        Assert.assertTrue("primeTo should be greater than primeFrom", primeTo > primeFrom);

        outStream.println(String.format("Calculating primes from %d to %d", primeFrom, primeTo));
        for (int i = primeFrom; i < primeTo; i++) {
            if (isPrime(i)) {
                outStream.println(i + " is a prime number!");
            }
        }
    }

    private boolean isPrime(int number) {
        for (int i = 2; 2*i < number; i++) {
            if (0 == number % i) {
                return false;
            }
        }
        return true;
    }

    public void setPrimeFrom(int primeFrom) {
        this.primeFrom = primeFrom;
    }

    public void setPrimeTo(int primeTo) {
        this.primeTo = primeTo;
    }

    public void setOutStream(PrintStream outStream) {
        this.outStream = outStream;
    }

}
